//ignore_for_file: file_names, slash_for_doc_comments, must_call_super, unnecessary_overrides, override_on_non_overriding_member, must_be_immutable, prefer_const_constructors, sized_box_for_whitespace, avoid_unnecessary_containers, avoid_print

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wifi/api/MusicApi.dart';
import 'package:flutter_wifi/entity/DeviceEntity.dart';
import 'package:flutter_wifi/entity/TrackEntity.dart';
import 'package:flutter_wifi/page/FFMouseRegion.dart';
import 'package:flutter_wifi/page/LimitMaxWidth.dart';
import 'package:flutter_wifi/upload/MusicFileManager.dart';
import 'package:flutter_wifi/view/TipView.dart';
import 'package:flutter_wifi/view/WebUploadView.dart';
import 'package:flutter_wifi/const/ImgConst.dart';
import 'package:flutter_wifi/const/MyColor.dart';
import 'package:flutter_wifi/language/LanguageValue.dart';
import 'package:flutter_wifi/upload/MusicUploadTask.dart';
import 'package:get/get.dart';
import 'package:mybase/base/abstract/IFFR.dart';
import 'package:mybase/base/tool/api/ApiUtils.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/extension/FFListExt.dart';
import 'package:mybase/base/tool/extension/FFNumExt.dart';
import 'package:mybase/base/tool/extension/FFStringExt.dart';
import 'package:mybase/base/tool/extension/FFWidgetExt.dart';
import 'package:mybase/base/tool/file/FFile.dart';
import 'package:mybase/base/tool/globalMethod/FFScreenValue.dart';
import 'package:mybase/base/tool/queue2/FFMultiTaskManager.dart';
import 'package:mybase/base/tool/web/FFWebHelp.dart';
import 'package:mybase/base/widget/layout/FFContainer.dart';
import 'package:mybase/base/widget/layout/FFImageButton.dart';
import 'package:mybase/base/widget/layout/FFLineContainer.dart';
import 'package:mybase/base/widget/layout/FFList.dart';
import 'package:mybase/base/widget/layout/FFTextButton.dart';
import 'package:mybase/base/widget/layout/FFTwoChild.dart';
import 'package:mybase/base/widget/page/FFWeb.dart';
import 'dart:html' as html;
import 'dart:ui' as ui;
import 'package:flutter/services.dart';

/**
 * WebBasePage 页面
 */
class WebBasePage extends FFWeb {
  String? name;

  WebBasePage({
    Key? key,
    this.name,
  }) : super(key: key);

  @override
  WebBasePageState createState() => WebBasePageState();
}

class WebBasePageState extends FFWebState implements FFIMultiTaskDelegate {
  /**固定写法 */
  @override
  WebBasePage get widget => super.widget as WebBasePage;

  /**固定写法end */

  // 本页面getx
  WebBasePageGetx getx = WebBasePageGetx();
  late html.DivElement _dropZone;

  @override
  void ffInitState() {
    super.ffInitState();
    FFMultiTaskManager().deleagte = this;
    dropInit();
  }

  // 第一帧结束后执行
  @override
  void ffFirstFrame() {
    // 将地址栏参数修改成原来的样子
    FFWebHelp.resetTitleAndPath(html.window);

    apiPhoneMusicList();
    if (FFEmpty.stringIsEmpty(getx.deviceName.value)) {
      apiDevice();
    }
  }

  apiDevice() async {
    IFFR<DeviceEntity> r = await MusicApi.device<DeviceEntity>();
    if (r.code != ApiUtils.okCode) return;

    getx.deviceName.value = r.data?.deviceName ?? "";
    html.document.title = getx.deviceName.value;
    getx.deviceEntity.value = r.data!;
    getx.update();
    setState(() {});
  }

  // 获取手机音乐列表
  Future<void> apiPhoneMusicList() async {
    IFFR<List<TrackEntity>> musicList =
        await MusicApi.getMusicList<List<TrackEntity>, TrackEntity>(page: '1');
    if (!musicList.isSuccess()) {
      TipView.show(getx.deviceEntity.value.Disconnected.toString());
      return;
    }
    getx.completeList.value = musicList.data ?? [];
    getx.update();
  }

  // 初始化拖拽
  dropInit() {
    _dropZone = html.DivElement()
      ..id = 'drop_zone'
      ..style.width = '100%'
      ..style.height = '100%'
      ..style.display = 'flex'
      ..style.alignItems = 'center'
      ..style.justifyContent = 'center';

    _dropZone.addEventListener('dragover', (event) {
      event.preventDefault();
      event.stopPropagation();
    });

    _dropZone.addEventListener('dragleave', (event) {
      event.preventDefault();
      event.stopPropagation();
    });

    _dropZone.addEventListener('drop', (event) async {
      event.preventDefault();
      final html.DataTransfer dataTransfer = (event as html.MouseEvent).dataTransfer;

      if (dataTransfer.files!.isNotEmpty) {
        final List<html.File>? files = dataTransfer.files;
        if (FFEmpty.listIsEmpty(files)) return;
        for (int i = 0; i < files.toLength; i++) {
          final html.File file = files![i];
          final reader = html.FileReader();
          reader.onLoadEnd.listen((e) {
            var data = reader.result as Uint8List;
            //file.size;
            MusicFileManager().addTask(
              data: data,
              fileName: file.name,
              getx: getx,
              size: file.size,
            );
          });
          reader.readAsArrayBuffer(file);
        }
      }
    });

    ui.platformViewRegistry.registerViewFactory("drop-zone-html", (int viewId) {
      return html.DivElement()..append(_dropZone);
    });
  }

  @override
  EdgeInsetsGeometry? get ffPadding => EdgeInsets.only(left: 40, top: 24, right: 40, bottom: 24);

  @override
  bool get ffHasBgWidget2 => true;

  @override
  Widget? ffBgWidget2(BuildContext context) {
    return Container(
      color: MyColor.c0F0F0F,
      child: HtmlElementView(
        viewType: "drop-zone-html",
      ),
    );
  }

  @override
  Widget? ffNavi(BuildContext context) {
    return LimitMaxWidth(
      child: FFLineContainer(
        direction: Axis.horizontal,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          FFImageButton(
            width: 48,
            heigth: 48,
            image: AssetImage("assets/common/logo.png"),
            borderRadius: BorderRadius.circular(12),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              border: Border.all(width: 1, color: MyColor.c333333),
            ),
          ),
          16.widthSpace,
          FFTextButton(
            text: getx.deviceEntity.value.MusicPlayer ?? "",
            fontSize: 20,
            fontWeight: FontWeight.w600,
            fontColor: MyColor.ffffff,
          ),
        ],
      ),
    );
  }

  // @override
  // Widget? ffNaviBottomFixedArea(BuildContext context) {
  //   return Container(
  //     height: 100,
  //     child: HtmlElementView(
  //       viewType: 'drop-zone-html',
  //     ),
  //   );
  // }

  @override
  bool get ffHasFloatWidget => super.ffHasFloatWidget;

  static double progress = 0;

  @override
  Widget ffBody(BuildContext context) {
    return LimitMaxWidth(
      child: FFLineContainer(
        direction: Axis.vertical,
        children: [
          // 提示文本
          FFTextButton(
            text: getx.deviceEntity.value.dragTracks,
            fontSize: 18,
            fontColor: MyColor.ffffff,
            maxLines: 10,
            fontWeight: FontWeight.w600,
            margin: EdgeInsets.only(top: 24),
          ),

          // 提示文本
          FFTextButton(
            text: getx.deviceEntity.value.dontClose,
            fontSize: 16,
            fontColor: MyColor.ffffff_60,
            maxLines: 10,
            margin: EdgeInsets.only(top: 8),
          ),

          // 上传 & 刷新
          FFLineContainer(
            direction: Axis.horizontal,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            margin: EdgeInsets.only(top: 40),
            children: [
              // 上传
              FFTwoChild(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  color: MyColor.c5C77FF,
                ),
                child1: FFImageButton(
                  width: 18,
                  heigth: 18,
                  image: AssetImage("assets/common/Upload@3x.png"),
                ),
                space: 10,
                child2: FFTextButton(
                  text: getx.deviceEntity.value.uploadMusic,
                  fontSize: 16,
                  fontLineHeight: 22 / 16.0,
                  fontColor: MyColor.ffffff,
                ),
                onClick: () async {
                  selectFiles();
                },
              ),

              // 刷新
              FFTwoChild(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  color: MyColor.c333333,
                ),
                child1: FFImageButton(
                  width: 18,
                  heigth: 18,
                  image: AssetImage("assets/common/Refresh@3x.png"),
                ),
                space: 10,
                child2: FFTextButton(
                  text: getx.deviceEntity.value.Refresh,
                  fontSize: 16,
                  fontLineHeight: 22 / 16.0,
                  fontColor: MyColor.ffffff,
                ),
                onClick: () {
                  ffFirstFrame();
                },
              ),
            ],
          ),

          // 列表区域
          FFLineContainer(
            isExpand: true,
            direction: Axis.vertical,
            margin: EdgeInsets.only(top: 24),
            decoration: BoxDecoration(
              border: Border.all(width: 1, color: MyColor.c333333),
            ),
            width: globalScreenWidth(context),
            children: [
              // 设备名称
              getx.build((x) => FFTextButton(
                    text: x.deviceName.value,
                    fontSize: 14,
                    fontColor: MyColor.ffffff,
                    maxLines: 4,
                    fontLineHeight: 20 / 14.0,
                    padding: EdgeInsets.symmetric(horizontal: 16, vertical: 11),
                    textVerticalCenter: true,
                    decoration: BoxDecoration(
                      color: MyColor.c1F1F1F,
                    ),
                  )),

              // 本地的列表
              FFContainer(
                isExpand: true,
                child: Container(
                  child: getx.build(
                    (x) => FFList(
                      space: 0,
                      endSpace: 60,
                      builder: (ctx, index) {
                        TrackEntity entity = x.completeList.value[index];
                        return FFMouseRegion(
                          builder: (hover) {
                            return FFLineContainer(
                              direction: Axis.horizontal,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              padding: EdgeInsets.symmetric(horizontal: 16),
                              decoration: BoxDecoration(
                                border: Border(bottom: BorderSide(width: 1, color: MyColor.c333333)),
                                color: hover ? Colors.white.withOpacity(0.06) : Colors.transparent,
                              ),
                              children: [
                                // icon
                                FFImageButton(
                                  width: 20,
                                  heigth: 20,
                                  image: AssetImage(ImgConst.imgLocal),
                                ),

                                // 文件名
                                FFTextButton(
                                  isExpand: true,
                                  text: entity.name,
                                  fontSize: 14,
                                  fontColor: MyColor.ffffff,
                                  textVerticalCenter: true,
                                  margin: EdgeInsets.only(left: 10),
                                ),

                                // 文件大小
                                FFTextButton(
                                  text: FFile.getFileSize(entity.size.toINT()),
                                  fontSize: 14,
                                  fontColor: MyColor.ffffff,
                                  textVerticalCenter: true,
                                ),

                                // 删除
                                FFTextButton(
                                  text: getx.deviceEntity.value.remove,
                                  padding: EdgeInsets.symmetric(horizontal: 6, vertical: 12),
                                  fontSize: 14,
                                  textVerticalCenter: true,
                                  fontColor: MyColor.ff5b4d,
                                  onClick: () async {
                                    IFFR r = await MusicApi.delete(sqlid: entity.sqlid.toString());
                                    if (r.isSuccess()) {
                                      x.completeList.remove(entity);
                                      x.update();
                                    } else {
                                      TipView.show(getx.deviceEntity.value.Disconnected ?? "Error");
                                    }
                                  },
                                ),

                                // 下载
                                FFTextButton(
                                  text: getx.deviceEntity.value.download,
                                  padding: EdgeInsets.symmetric(horizontal: 6, vertical: 12),
                                  fontSize: 14,
                                  textVerticalCenter: true,
                                  fontColor: MyColor.c5C77FF,
                                  onClick: () async {
                                    String url = "${ApiUtils.appApi.env_product}${entity.path}";

                                    var heart = await MusicApi.heart();
                                    if (!heart.isSuccess()) {
                                      TipView.show(getx.deviceEntity.value.Disconnected ?? "Error");
                                      return;
                                    }

                                    var fileName = entity.path?.split("/").last;
                                    if (FFEmpty.stringIsEmpty(fileName)) {
                                      fileName = entity.path;
                                    }

                                    /// 下载文件
                                    final anchor = html.AnchorElement(href: url)
                                      ..setAttribute('download', fileName ?? "music")
                                      ..click();
                                  },
                                ),
                              ],
                            );
                          },
                        );
                      },
                      itemCount: x.completeList.value.toLength,
                    ),
                  ),
                ).toStack(
                  children: [
                    // 进度悬浮窗
                    getx.build((x) => Positioned(
                          right: 0,
                          bottom: 0,
                          child: FFEmpty.listIsEmpty(x.uploadList)
                              ? Container()
                              : WebUploadView(
                                  getx: getx,
                                ),
                        )),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 选择文件
  selectFiles() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      allowMultiple: true,
      type: FileType.audio,
    );

    if (result != null) {
      for (var file in result.files) {
        Uint8List? data = file.bytes;
        print(file.name);
        print(file.size);
        print(file.extension);

        if (data == null) {
          continue;
        }

        MusicFileManager().addTask(
          data: data,
          fileName: file.name,
          getx: getx,
          size: file.size,
        );
      }
    } else {
      // User canceled the picker
    }
  }

  @override
  void allTaskComplete() {
    getx.uploadList.value = [];
    getx.completeCount.value = 0;
    getx.update();

    apiPhoneMusicList();
  }
}

// Getx
class WebBasePageGetx extends GetxController {
  // 上传的数组
  var uploadList = <MusicUploadTask>[].obs;
  var completeList = <TrackEntity>[].obs;
  var deviceName = "".obs;
  var deviceEntity = DeviceEntity().obs;

  // 已经上传的数量
  var completeCount = 0.obs;

  @override
  void onInit() {
    super.onInit();
  }

  // 动态变化的用这个包裹
  Widget build(Widget Function(WebBasePageGetx x) child) {
    return GetBuilder<WebBasePageGetx>(
      init: this, // 局部控制器
      builder: (ctl) {
        return child(ctl);
      },
    );
  }
}
